#!/bin/bash

cd "$(dirname "$0")"

# --- --- --- --- --- 参数 --- --- --- --- --- --- #

# - 仓库
repository=registry-intl.cn-hongkong.aliyuncs.com
# - 项目
project=webgo
# - 应用
app=server
# - 版本
version=1.0.0

# - - 工作路径
work=/home/$project/dev/software/$app
# - - 镜像名
image=$repository/$project/$app:$version

# --- --- --- --- --- 编译 --- --- --- --- --- --- #

# O. 
cd ../../..
go build -o ./dev/docker/$app/service index.go

if [ $? -ne 0 ]; then
    exit -1
fi

cd -

# --- --- --- --- --- 指令 --- --- --- --- --- --- #

# A. 测试
if [ "$1" = "debug" ]; then

    export ADMIN_PASSWORD="123456"

    export MONGO_URL="localhost:16010"
    export MONGO_DATABASE="webgo"
    export MONGO_USERNAME="admin"
    export MONGO_PASSWORD="admin_8981409"

    export HTTP_SERVER_URL=":16000"
    export HTTP_SERVER_FILE="./file"
    export HTTP_SERVER_HTML="./html"
    export HTTP_SERVER_JWTKEY="8981409"
    export HTTP_SERVER_JWTKEY_EXPIRY_TIME=3600

    ./service

# B. 构建
elif [ "$1" = "build" ]; then

    # 1. 打包
    docker build -t $image -f ./Dockerfile .
    # 2. 上传
    docker push $image

# C. 运行
elif [ "$1" = "run" ]; then

    # 1. 下载新容器
    docker install $project-$app
    # 2. 停止旧容器
    docker stop $project-$app > /dev/null 2>&1
    # 3. 删除旧容器
    docker rm $project-$app > /dev/null 2>&1
    # 4. 启动
    docker run -itd --name $project-$app \
        \
        --restart=always \
        \
        -v $work/file:$work/file \
        -v $work/html:$work/html \
        \
        $image

# 指令不存在
else
    exit 1
fi
